package com.doyens.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.gmall.model.product.*;
import com.doyens.gmall.product.mapper.*;
import com.doyens.gmall.product.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MangeServiceImpl implements ManageService {

    @Autowired
    private BaseAttrInfoMapper baim;// 平台属性mapper
    @Autowired
    private BaseAttrValueMapper bavm;// 平台属性对应的value mapper
    @Autowired
    private BaseCategory1Mapper bc1m; // 一级分类
    @Autowired
    private BaseCategory2Mapper bc2m; // 二级分类
    @Autowired
    private BaseCategory3Mapper bc3m; // 三级分类
    @Autowired
    private SpuInfoMapper sim; // 商品表
    @Autowired
    private BaseTrademarkMapper btm; //品牌表
    @Autowired
    private BaseSaleAttrMapper bsam; //基本销售属性表
    @Autowired
    private SpuImageMapper spuImageMapper;      // spu图片表
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;    //spu销售属性表
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;  //spu销售属性值表
    @Autowired
    private SkuInfoMapper skuInfoMapper; //库存单元表
    @Autowired
    private SkuImageMapper skuImageMapper;//库存单元图片表
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper; //sku平台属性值关联表
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper; //sku销售属性值
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;// 获取分类信息

    @Override
    public List<BaseCategory1> getCategory1() {
        return bc1m.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1id) {
        return bc2m.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2id) {
        return bc3m.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2id));
    }

    /**
     * 查询出平台属性
     * 根据第一层,第二层,第三层id获取平台属性
     *
     * @param category1Id
     * @param category2Id
     * @param category3Id
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baim.selectBaseAttrInfoList(category1Id, category2Id, category3Id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //根据id是否存在,有id就是修改 没有就是添加
        if (baseAttrInfo.getId() != null) {
            //执行修改
            baim.updateById(baseAttrInfo);
            //将因为修改后关联的属性表可能不匹配 进行删除重新添加
            bavm.delete(new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId()));
        } else {
//            没有id 是添加
            baim.insert(baseAttrInfo);
        }
        //不管是添加 都要将平台属性值的数据 添加到base_attr_value表里
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            //将作为连接的attr_id给他
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            //执行平台属性值的数据 添加
            bavm.insert(baseAttrValue);
        }
    }

    @Override
    public List<BaseAttrValue> findAttrValueListByid(Long attrId) {
//         根据属性id查询出平台属性值
        return bavm.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
    }

    /**
     * 根据id查平台属性
     *
     * @param attrId
     */
    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //根据id查对应的平台属性
        BaseAttrInfo baseAttrInfo = baim.selectById(attrId);
        if (baseAttrInfo != null) {//判断这个对象是否为空
            //根据这个id查询关联的平台属性值
            List<BaseAttrValue> attrValueListByid = findAttrValueListByid(attrId);
            if (attrValueListByid != null || attrValueListByid.size() > 0) {//判断有没有对应的平台属性值
                baseAttrInfo.setAttrValueList(attrValueListByid);//有就放进实体类里一起返回
            }
        }
        return baseAttrInfo;
    }

    /**
     * SpuInfo进行分页查询
     * page 当前页数
     * limit 页容量
     * spuInfo 根据category3Id分页查询
     *
     * @param page
     * @param spuInfo
     */
    @Override
    public IPage<SpuInfo> getSpuInfoPage(Page<SpuInfo> page, SpuInfo spuInfo) {
        return sim.selectPage(page, new QueryWrapper<SpuInfo>()
                //根据第三层id查询
                .eq("category3_Id", spuInfo.getCategory3Id())
                //排序
                .orderByDesc("id")
        );
    }

    /**
     * 查询全部品牌
     */
    @Override
    public List<BaseTrademark> getTrademarkList() {
        return btm.selectList(null);
    }

    @Override
    public IPage<BaseTrademark> getTrademarkPage(Page<BaseTrademark> baseTrademarkPage) {
        return btm.selectPage(baseTrademarkPage, null);
    }

    @Override
    public void saveTrademarkPage(BaseTrademark baseTrademark) {
        //添加
        btm.insert(baseTrademark);


    }

    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return btm.selectOne(new QueryWrapper<BaseTrademark>().eq("id", id));
    }

    @Override
    public void removeTrademarkByid(Long id) {
        btm.delete(new QueryWrapper<BaseTrademark>().eq("id", id));
    }

    @Override
    public void updateTrademark(BaseTrademark baseTrademark) {
        btm.updateById(baseTrademark);
    }

    @Override
    public List<BaseSaleAttr> getbaseSaleAttr() {
        return bsam.selectList(null);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuInfo spuInfo) {
        sim.insert(spuInfo);
        //  spu_sale_attr	销售属性表（多条）
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);//添加
            }
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                //添加销售属性
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        //添加销售属性值表
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
    }

    @Override
    public List<SpuImage> getSpuImageByid(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    @Override
    public List<SpuSaleAttr> getspuSaleAttrListspuid(Long spuId) {
        return spuSaleAttrMapper.getspuSaleAttrListspuid(spuId);
    }

    /**
     * @param skuInfo 添加
     *                涉及的表：
     *                * //        sku_info（库存单元表）
     *                * //        sku_attr_value（平台属性值关联表）
     *                * //        sku_sale_attr_value（销售属性值关联表）
     */
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        skuInfoMapper.insert(skuInfo);
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            for (SkuImage skuImage : skuImageList) {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }
    }

    /**
     * 执行分页查询sku
     *
     * @param page1
     * @return
     */
    @Override
    public IPage<SkuInfo> getSkuInfoList(Page<SkuInfo> page1) {
        return skuInfoMapper.selectPage(page1, new QueryWrapper<SkuInfo>().orderByDesc("id"));
    }

    /**
     * 上架
     *
     * @param skuId
     */
    @Override
    public void onSale(Long skuId) {
        //更改那个销售状态即可
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
    }

    /**
     * 下架
     *
     * @param skuId
     */
    @Override
    public void cancelSale(Long skuId) {
        //更改那个销售状态即可
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    /**
     * 获取sku基本信息与图片信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo sku_id = skuInfoMapper.selectById(skuId);
        List<SkuImage> skuImages = skuImageMapper.selectList(new QueryWrapper<SkuImage>()
                .eq("sku_id", skuId));
        sku_id.setSkuImageList(skuImages);
        return sku_id;
    }

    /**
     * 获取分类信息
     *
     * @param category3Id
     * @return
     */
    @Override
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 获取sku价格
     *
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null) {
            return skuInfo.getPrice();
        }
        return new BigDecimal(0);
    }

    /**
     * 根据spuId，skuId 查询销售属性集合
     *
     * @param skuId
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    /**
     * 根据spuId 查询map 集合数据
     *
     * @param spuId
     */
    @Override
    public Map getSkuValueIdsMap(Long spuId) {
        Map map = new HashMap<>();
        List<Map> maps = spuSaleAttrMapper.selectSaleAttrValuesBySpu(spuId);
        //循环
        System.out.println(maps);
        if (!CollectionUtils.isEmpty(maps)) {
            for (Map map1 : maps) {
                //改为 key = 116|119 ,value = 42格式 存到map集合中
                map.put(map1.get("value_ids"), map1.get("sku_id"));
            }
        }
        return map;
    }

}
